package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import comment.ApplicationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询所有的菜品信息
 */
@WebServlet("/dishlist")
public class DishListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Dish> list = new ArrayList<>();
        //是否下架（非必传）
        String isdownStr = req.getParameter("isdown");
        Integer isdown = -1;  //是否下架
        if(!StrUtil.isBlank(isdownStr) && isdownStr.equals("0")){  //有效参数，表示查询的是未下架的菜品
            isdown = 0;

        }
        //连接数据库
        Connection connection = DBUtil.getConnection();
        String sql = "select * from dish";
        if(isdown == 0){
            sql += " where isdown=?";
        }
        PreparedStatement statement = connection.prepareStatement(sql);
        if(isdown == 0){
            statement.setInt(1,0);
        }
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            Dish dish = new Dish();
            dish.setDid(resultSet.getInt("did"));
            dish.setName(resultSet.getString("name"));
            dish.setPrice(resultSet.getBigDecimal("price"));
            dish.setIsdown(resultSet.getInt("isdown"));
            dish.setCreatetime(resultSet.getString("createtime"));
            dish.setSelect(false);
            list.add(dish);
        }
        DBUtil.close(resultSet,statement,connection);
        resp.setContentType(ApplicationVariable.APPLICATION_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(200,list,"")));
    }
}
